const db = require('../db/index')
// const path = require('path')
const bcrypt = require('bcryptjs')
// 获取全部用户信息
exports.getAllUserInfo = (req, res) => {
  const sql = 'select * from user'
  db.query(sql, (err, results) => {
    if (err) return res.cc(err)
    if (results.length === 0) return res.cc('暂无用户信息')
    results.forEach(item => item.password = '')
    res.send({
      status: 0,
      message: '获取用户信息成功',
      data: results
    })
  })
}

// 获取全部维修员信息
exports.getAllMaintainerInfo = (req, res) => {
  const sql = 'select * from maintainer ORDER BY `status`'
  db.query(sql, (err, results) => {
    if (err) return res.cc(err)
    if (results.length === 0) return res.cc('暂无维修员信息')
    results.forEach(item => item.password = '')
    res.send({
      status: 0,
      message: '获取成功',
      data: results
    })
  })
}

// 获取全部管理员信息
exports.getAllAdminInfo = (req, res) => {
 const sql = 'select * from admin where status <> "2"'
  db.query(sql, (err, results) => {
    if (err) return res.cc(err)
    if (results.length === 0) return res.cc('暂无管理员信息')
    results.forEach(item => item.password = '')
    res.send({
      status: 0,
      message: '获取成功',
      data: results
    })
  })
}

// 获取全部订单信息
exports.getAllOrderInfo = (req, res) => {
    const sql = `SELECT
    o.id as id,
	o.appointmentDate,
	o.startTime,
    o.endTime,
    o.linkman,
    o.phone,
	o.failure,
    o.remark,
    o.order_status,   
	o.create_time,
	o.take_time,
	o.done_time,
	o.maintainer_id,
	m.nickname as'maintainer_nickname',	
	m.phone as 'maintainer_phone',
	s.service_name,
	s.service_img,
	s.service_pice,
	a.districts,
	a.city,
	a.county,
	a.full_address
FROM
	orderinfo o,
	maintainer m,
	repair_service s,
  address a
WHERE
	o.serviceAddress = a.id
AND
 (o.maintainer_id = m.id OR o.maintainer_id IS NULL)
AND
	o.service_id = s.id`
    db.query(sql, req.query.id, (err, result) => {
        if(err) res.cc(err)
        if(result.length === 0) {
           return res.cc('获取失败')
        }
        res.send({
            status:0,
            message:'获取成功',
            data: result
        })
    })
}

// 修改密码
exports.changePwd = (req, res) => {
    const { oldPwd, newPwd } = req.body
    const selectSql = 'select password from admin where id=?'
    db.query(selectSql, req.user.id, (err,results) => {
        if(err) return res.cc(err)
        if(results.length !== 1) return res.cc('用户不存在')
        // TODO1：判断密码是否正确----bcrypt.compareSync(用户提交的密码, 数据库的密码)
        const compareResults = bcrypt.compareSync(oldPwd, results[0].password)
        if(!compareResults) return res.cc('修改失败，原密码错误')
        // 对密码进行加密
        const password = bcrypt.hashSync(newPwd, 10)
        const sql = 'update admin set password=? where id=?'
        db.query(sql, [password, req.user.id], (err, results) => {
            if(err) return res.cc(err)
            // console.log(results);
            if(results.affectedRows !== 1) return res.cc('修改密码失败')
            res.cc('修改密码成功',0)
        })
    })
}

// 添加管理员
exports.addAdmin = (req, res) => {
  const data = req.body
    let sql = 'select id from admin where adminName=?'
    db.query(sql, req.body.adminName, (err, results) => {
        if(err) return res.cc(err)
        if(results.length === 1) return res.cc('用户名已存在')
        // 对密码进行加密
        const password = bcrypt.hashSync("123456", 10)
        data.password = password
        sql = 'insert into admin set ?'
        db.query(sql, data, (err, results) => {
            if(err) return res.cc(err)
            if(results.affectedRows !== 1) return res.cc('添加失败')
            res.cc('添加成功', 0)
        })
      }
)}

// 设置账号状态
exports.updateAdmin = (req, res) => {
  // 1-->用户，2-->维修员， 3-->管理员
  const role = req.body.role
  console.log(req.body.role+'----');
  let sql = ''
  if(role === '1') {
    sql = 'update user set status=? where id=?'
  } else if(role === '2') {
    sql = 'update maintainer set status=? where id=?'
  } else if(role === '3') {
    sql = 'update admin set status=? where id=?'
  }
    db.query(sql, [req.body.status, req.body.id], (err, results) => {
        if(err) return res.cc(err)
        if(results.affectedRows !== 1) return res.cc('修改失败')
        res.cc('修改成功', 0)
    })
}

// 审核维修员
exports.checkMaintainer = (req, res) => {
    const sql = 'update maintainer set status=? where id=?'
    db.query(sql, [req.body.status, req.body.id], (err, results) => {
        if(err) return res.cc(err)
        if(results.affectedRows !== 1) return res.cc('审核失败')
        res.cc('审核成功', 0)
    })
}

// 重置密码
exports.resetPwd = (req, res) => {
  // 1-->用户，2-->维修员， 3-->管理员
  const role = req.body.role
  let sql = ''
  if(role === '1') {
    sql = 'update user set password=? where id=?'
  } else if(role === '2') {
    sql = 'update maintainer set password=? where id=?'
  } else if(role === '3') {
    sql = 'update admin set password=? where id=?'
  }
  db.query(sql, [bcrypt.hashSync("123456", 10), req.body.id], (err, results) => {
    if(err) return res.cc(err)
    if(results.affectedRows !== 1) return res.cc('重置失败')
    res.cc('重置成功', 0)
  })
  
}

// 获取统计信息
exports.getCount = (req, res) => {
const sql = `select u.uCount,m.mCount,o.oCount
  from(
      (select COUNT(*) as uCount from user) u,
      (select COUNT(*) as mCount from maintainer) m,
      (select COUNT(*) as oCount from orderinfo) o
  )`
  db.query(sql, (err, results) => {
    if(err) return res.cc(err)
    // if(results.length === 0) return res.cc('没有数据',0)
    const data = results[0]
    const str = `SELECT
      sum(p.service_pice) sum_1,
      sum(r.service_pice) sum_2
    FROM
      orderinfo p,
      repair_service r
    WHERE
      to_days(done_time) = to_days(now())
    AND r.id = p.service_id`
    db.query(str, (err, result) => {
      if(err) return res.cc(err)
      if(result.length === 0 && results.length === 0) return res.cc('没有数据',0)
      data.totalPice = result[0].sum_1 + result[0].sum_2
      res.send({
      status: 0,
      message: '获取成功',
      data: data
    })
    
    })
    
  })
}